package top.cardone.context.util;

import com.google.common.collect.Maps;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.Map;

/**
 * 消息格式工具类
 *
 * @author yao hai tao
 */
public class MessageFormatUtils {
    /**
     * 消息格式化映射
     */
    private static Map<String, MessageFormat> messageFormatMap = Maps.newConcurrentMap();

    /**
     * 获取消息
     *
     * @param pattern 消息格式字符串
     * @return 消息格式
     */
    public static MessageFormat getMessageFormat(String pattern) {
        return getMessageFormat(pattern, org.springframework.context.i18n.LocaleContextHolder.getLocale());
    }

    /**
     * 获取消息
     *
     * @param pattern 消息格式字符串
     * @param locale  时区
     * @return 消息格式
     */
    public static MessageFormat getMessageFormat(String pattern, Locale locale) {
        String messageFormatKey = pattern + locale.getDisplayName();

        MessageFormat messageFormat = messageFormatMap.get(messageFormatKey);

        if (messageFormat == null) {
            messageFormat = new MessageFormat(pattern, locale);

            messageFormatMap.put(messageFormatKey, messageFormat);
        }

        return messageFormat;
    }
}
